<template>
    <div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.sName" placeholder="名称" class="handle-input mr10"></el-input>
                <el-date-picker v-model="query.adYearMonth" type="month" placeholder="考勤月份" class="mr10"  value-format="yyyy-MM" format="yyyy-MM"> </el-date-picker>
                <el-select v-model="query.adReceivalFlag" placeholder="是否已回款" class="mr10" filterable style="width: 8%">
                  <el-option  key="" label="" value="" />
                  <el-option  key="1" label="是" :value="true" />
                  <el-option  key="0" label="否" :value="false" />
                </el-select>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-download" class="handle-del floatr" @click="downMb" v-if="roleId !=8"> 模板下载</el-button>
            </div>
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column type="index" label="ID" width="55" align="center" ></el-table-column>
                <el-table-column prop="sName" label="姓名"></el-table-column>
                <el-table-column prop="adYearMonth" label="考勤月份"></el-table-column>
                <el-table-column prop="adDueatt" label="当月应出勤"></el-table-column>
                <el-table-column prop="adAttend" label="实际出勤日"></el-table-column>
                <el-table-column prop="adSalary" label="当月薪资"></el-table-column>
                <el-table-column prop="adDuerec" label="应回款金额"></el-table-column>
                <el-table-column label="操作" width="220" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                v-if="roleId !=8"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            v-if="roleId ==8"
                            icon="el-icon-edit-outline"
                            @click="handleSelect(scope.$index, scope.row)"
                        >详情</el-button>
                        <el-upload
                            v-if="roleId !=8"
                            :show-file-list="false"
                            class="avatar-uploader"
                            :before-upload="beforeUpload"
                            :on-success="onSuccess"
                            :on-error="onError"
                            multiple
                            :disabled="importDisabled"
                            :headers="fileHeaders"
                            style="display: inline-flex;margin-right: 10px;"
                            :action="$host+'/rest/attendance/uploadExcel?userId='+scope.row.adUserId+'&adId='+scope.row.adId">
                          <el-button size="small" :disabled="importDisabled" type="text" :icon="importDataIcon" style="margin-left: 1vw">
                            {{importDataText}}
                          </el-button>
                        </el-upload>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.pageIndex"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%" :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="150px">
                <el-form-item label="姓名" prop="sName" >
                    <el-input maxlength="20" v-model="form.sName" v-bind:readonly="true" disabled></el-input>
                </el-form-item>
                <el-form-item label="当月应出勤" prop="adDueatt" >
                  <el-input maxlength="20" v-model="form.adDueatt" oninput="value=value.replace(/[^\d.]/g,'')" :onblur="calculateSalaryFun()"></el-input>
                </el-form-item>
                <el-form-item label="实际出勤日" prop="adAttend" >
                  <el-input maxlength="20" v-model="form.adAttend" oninput="value=value.replace(/[^\d.]/g,'')" :onblur="calculateSalaryFun()"></el-input>
                </el-form-item>
                <el-form-item label="当月薪资" prop="adSalary" >
                  <el-input maxlength="20" v-model="form.adSalary" oninput="value=value.replace(/[^\d.]/g,'')" disabled></el-input>
                </el-form-item>
                <el-form-item label="应回款金额" prop="adDuerec" >
                  <el-input maxlength="20" v-model="form.adDuerec" oninput="value=value.replace(/[^\d.]/g,'')" disabled></el-input>
                </el-form-item>
                <el-form-item label="备注">
                  <el-input type="textarea" rows="5" v-model="form.adRemarks" maxlength="200"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer" v-show="isEditFlag">
                <el-button @click="butCancel">取 消</el-button>
                <el-button type="primary" @click="saveEdit('form')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { selectPage,addAttendance,updateAttendance,getAttendanceByID} from '../../api/attendance';
    import { downLoadTemplate} from '../../api/utils';
    import { getStaff1ByID} from '../../api/staff1';
    import {_dateFormat} from '../../utils/tool';
    import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
    export default {
        name: 'basetable',
        components: { ElImageViewer },
        data() {
            return {
                query: {
                    status:'',
                    adStaffType:'1', // 只差合同范围得
                    pageIndex: 1,
                    pageSize: 10
                },
                fileHeaders: {
                  'X-Token': localStorage.getItem("X-Token")
                },
                roleId:localStorage.getItem("ms_userrole"),
                previewFlg:false,
                previewSrc: '',
                tableData: [],
                multipleSelection: [],
                groupList:[],
                editVisible: false,
                isEditFlag: false,
                pageTotal: 0,
                form: {
                   adId:"",
                   adDueatt:"",
                   adAttend:"",
                   adSalary:"",
                   adEstimate:"",
                   adCollection:"",
                   adDuerec:"",
                   adReceival:"",
                   adInvoice:"",
                   adRemarks:"",
                   createTime:"",
                   createUserId:"",
                   updateTime:"",
                   updateUserId:"",
                   adUserId:"",
                   adYearMonth:""
                },
                userInfo:{},
                rules:{
                    title :[{required: true, message: '名称不能为空', trigger: 'blur'}],
                    type :[{required: true, message: '请选择所属位置', trigger: 'blur'}],
                },
                // 导入按钮的文本
                importDataText: '导入数据',
                // 导入按钮的图标
                importDataIcon: 'el-icon-upload2',
                // 导入按钮是否被禁用
                importDisabled: false,
                idx: -1,
                id: -1,
            };
        },
        created() {
            addAttendance(this.form).then(res => {
              this.getData();
              this.butCancel();
            }).catch((res) => {
              this.$message.error(res.errorMsg);
            });
            this.getData();
        },
        filters:{
            //格式化后台传过来的时间戳
            dateFormat(time) {
                if(!time){
                  return  ""
                }
                let date = new Date(time);
                return _dateFormat(date,'yyyy-MM-dd')
            },
            formatBoolean: function (cellValue) {
              var ret = ''  //你想在页面展示的值
              if (cellValue) {
                ret = "是"  //根据自己的需求设定
              } else {
                ret = "否"
              }
              return ret;
            },
        },
        methods: {
          // 获取list
          getData() {
              selectPage(this.query).then(res => {
                  this.tableData = res.items;
                  this.pageTotal = res.total ;
              });
          },
              // 触发搜索按钮
          handleSearch() {
            if(this.query.adEstimate){
              this.query.adEstimate = this.query.adEstimate + "-01";
            }
              this.$set(this.query, 'pageIndex', 1);
              this.getData();
          },
          // 查询
          getAttendanceByID(row){
            var _that =this;
            getAttendanceByID(row.adId).then(res => {
             _that.form = res;
              this.getStaff1ByID(row.adUserId);
            });
          },
          // 查询用户信息
          getStaff1ByID(id){
            var _that =this;
            getStaff1ByID(id).then(res => {
              _that.userInfo = res;
            });
          },
          // 多选操作
          handleSelectionChange(val) {
              this.multipleSelection = val;
          },
          // 详情操作
          handleSelect(index, row) {
            this.idx = index;
            this.editVisible = true;
            this.isEditFlag = false;
            this.getAttendanceByID(row);
          },
          // 编辑操作
          handleEdit(index, row) {
              this.idx = index;
              this.editVisible = true;
              this.isEditFlag = true;
              this.getAttendanceByID(row);
          },
          //新增操作
          addSysRole() {
              this.editVisible = true;
              Object.keys(this.form).forEach(key => (this.form[key] = ''));
          },
          // 计算薪资
          calculateSalaryFun(){
            if(this.form.adDueatt  && this.form.adAttend ){
              //实际出勤/当月应出勤*薪资=当月薪资
              this.form.adSalary = ((this.form.adAttend/this.form.adDueatt)*this.userInfo.salary).toFixed(2);
              //实际出勤/当月应出勤*单价=当月薪资
              this.form.adDuerec = ((this.form.adAttend/this.form.adDueatt)*this.userInfo.price).toFixed(2);
            }
          },
          // 保存编辑
          saveEdit(formData) {
              var that = this;
              this.$refs[formData].validate((valid) => {
                  if (valid) {
                      if(!this.form.adReceivalFlag){
                        this.form.adCollection = null
                      }else{
                        if(!this.form.adDueatt){
                          this.$message.error("当月应出勤不能为空");
                        }
                        if(!this.form.adCollection ){
                          this.$message.error("实际回款日不能为空");
                        }
                        if(!this.form.adReceival){
                          this.$message.error("实际回款不能为空");
                        }
                      }
                      if(that.form.adId != null && that.form.adId != "" ){
                          // 编辑
                          updateAttendance(this.form).then(res => {
                              this.$message.success("保存成功");
                              this.getData();
                              this.butCancel();
                          }) .catch((res) => {
                              this.$message.error(res.errorMsg);
                          });
                      }
                  }
              })
          },
          // 导入文件失败后回调
          onError() {
            this.importDataText = '导入数据';
            this.importDataIcon = 'el-icon-upload2';
            this.importDisabled = false;
            this.initEmps();
            this.$message.success("导入失败！");
          },
          // 导入文件成功后回调
          onSuccess() {
            // 成功后文本修改为原来的导入数据
            this.importDataText = '导入数据';
            // 图标修改
            this.importDataIcon = 'el-icon-upload2';
            // 将上传组件改为允许使用
            this.importDisabled = false;
            // 调用刷新数据的方法
            this.getData();
            // message 弹出消息
            this.$message.success("导入成功！");
          },
          // 上传文件调用
          beforeUpload() {
            // 将文本修改为正在导入
            this.importDataText = '正在导入';
            // 修改其图标
            this.importDataIcon = 'el-icon-loading';
            // 将其上传组件暂时禁用
            this.importDisabled = true;
          },
          // 模板下载
          downMb(){
              downLoadTemplate().then((res) => {
                console.log(res)
                const content = res
                const blob = new Blob([content]) // 构造一个blob对象来处理数据
                const fileName = '员工考勤模板.xlsx' // 导出文件名
                // 对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
                // IE10以上支持blob但是依然不支持download
                if ('download' in document.createElement('a')) { // 支持a标签download的浏览器
                  const link = document.createElement('a') // 创建a标签
                  link.download = fileName // a标签添加属性
                  link.style.display = 'none'
                  link.href = URL.createObjectURL(blob)
                  document.body.appendChild(link)
                  link.click() // 执行下载
                  URL.revokeObjectURL(link.href) // 释放url
                  document.body.removeChild(link) // 释放标签
                } else { // 其他浏览器
                  navigator.msSaveBlob(blob, fileName)
                }
              }).catch((error) => {
                console.log(error)
              })
          },
          butCancel(){
              this.editVisible = false;
              Object.keys(this.form).forEach(key => (this.form[key] = ''));
          },
          // 分页导航
          handlePageChange(val) {
              this.$set(this.query, 'pageIndex', val);
              this.getData();
          }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }
    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .table {
        width: 100%;
        font-size: 14px;
    }
    .mr10 {
        margin-right: 10px;
    }
    .floatr {
        float: right;
    }
</style>